package com.example.student_blocket;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class AdsActivity extends Activity {
	
	private List<Ads> adsList = new ArrayList<Ads>();

	private final String LOAD_ADS = Singleton.getInstance().getHOST() +"shop-app/select-all-ads.php";
	private final boolean DEBUG = Singleton.getInstance().isDebug();
	private ListView listView;
	private ArrayList<AdsListDetails> ads_list;
	private Misc misc = new Misc();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_ads);
		setTitle("Student Ads");
		
		if (!DEBUG) {
			ads_list = new ArrayList<AdsListDetails>();
			listView = (ListView) findViewById(R.id.listRecentAds);
			new LoadAds().execute();
			
			listView.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					AdsListDetails opas = ads_list.get(position);
					String selectedID = opas.getId();
					Intent intent = new Intent(AdsActivity.this,AdsDetailActivity.class);
					intent.putExtra("id", selectedID);
					startActivity(intent);
				}
			});
		} else {
			populateAdsList();
			populateListView();
			registerClickCallBack();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    // Inflate the menu items for use in the action bar
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.ads, menu);
	    return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item){
			switch(item.getItemId()){
			case R.id.addads_btn_postannewad:
			startActivity(new Intent(AdsActivity.this,AddAdActivity.class));
			finish();
			return true;
			case R.id.addads_btn_myprofile:
				startActivity(new Intent(AdsActivity.this,UserProfileActivity.class));
				finish();
				return true;
			case R.id.addads_btn_search:
				startActivity(new Intent(AdsActivity.this, SearchActivity.class));
				finish();
				return true;
			}
			return false;
	}

	private void populateAdsList() {
		adsList.add(new Ads("Bed For Sale",500,"Category_furniture",20140309,R.drawable.bed));
		adsList.add(new Ads("Table For Sale",300,"Category_furniture",20140309,R.drawable.table));
		adsList.add(new Ads("Chair For Sale",500,"Category_furniture",20140309,R.drawable.chair));
	}

	private void populateListView() {
		ArrayAdapter<Ads> adapter = new MyListAdapter();
		ListView list = (ListView) findViewById(R.id.listRecentAds);
		list.setAdapter(adapter);
	}
	
	private class MyListAdapter extends ArrayAdapter<Ads>{
		public MyListAdapter(){
			super(AdsActivity.this,R.layout.item_view,adsList);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			//make sure we have a view to work with(may have been given null)
			View itemView = convertView;
			if(itemView == null){
				itemView = getLayoutInflater().inflate(R.layout.item_view, parent,false);
			}
			//Find the ad to work with 
			Ads currentAd = adsList.get(position);
			
			//Full the view
			ImageView imageView = (ImageView)itemView.findViewById(R.id.image);
			imageView.setImageResource(currentAd.getIconId());;

			TextView detailText = (TextView) itemView.findViewById(R.id.itemDetails);
			detailText.setText(currentAd.getTitle());
			
			return itemView;
			
		}
		
	}
	private void registerClickCallBack() {
		ListView list = (ListView) findViewById(R.id.listRecentAds);
		list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View ViewClicked, int position,
					long id) {
				Ads clickedAds = adsList.get(position);
				String message = "You have selected " + position + "Which is Title " + clickedAds.getTitle();
				Toast.makeText(AdsActivity.this,message,Toast.LENGTH_LONG).show();
				startActivity(new Intent(AdsActivity.this,AdsDetailActivity.class));
				
			}
		});
	}
	
	private class LoadAds extends AsyncTask<String, String, Boolean> {
		private ProgressDialog pDialog;
		@Override
		protected void onPreExecute() {
	        super.onPreExecute();
	        pDialog = new ProgressDialog(AdsActivity.this);
	        pDialog.setMessage("Loading Ads...");
	        pDialog.setIndeterminate(false);
	        pDialog.setCancelable(false);
	        pDialog.show();
	    }
		@Override
		protected Boolean doInBackground(String... params) {
			JSONParser jParser = new JSONParser();
			List<NameValuePair> values = new ArrayList<NameValuePair>();
            JSONObject json = jParser.makeHttpRequest(LOAD_ADS, values);
            try {
                int success = json.getInt("affected");
 
                if (success == 1) {
                	JSONArray ads = json.getJSONArray("ads");
                	
                    for (int i = 0; i < ads.length(); i++) {
                        JSONObject c = ads.getJSONObject(i);
 
                        String id = "" + c.getInt("id");
                        String title = c.getString("title");
                        String price = c.getString("price");
                        String image = c.getString("image");
                        String date = c.getString("date");
                        String category = c.getString("category");
                        String description = c.getString("description");
                        String owner = c.getString("owner");
                        
                        Bitmap imageBitmap = misc.getImage(image);
                        AdsListDetails adsDetails = new AdsListDetails(id, title, price, category, date, imageBitmap, description, owner);
                        ads_list.add(adsDetails);
                    }
                    return true;
                } else {
                    return false;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
 
            return null;
        }
 
		@Override
		protected void onPostExecute(Boolean op) {
			pDialog.dismiss();
            if (op) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Adapter adapter = new Adapter(getApplicationContext(), ads_list);
						listView.setAdapter(adapter);
					}
				});
			} else {
				misc.showErrorMessage("No Ads Available!", getApplicationContext());
			}
        }
	}
}
